package cn.ccccltd.waf.message.web.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import cn.ccccltd.waf.message.constant.MessageConstants;
import cn.ccccltd.waf.message.init.AppInit;
import cn.ccccltd.waf.message.model.result.Data;
import cn.ccccltd.waf.message.model.result.MessageResult;
import cn.ccccltd.waf.message.model.vo.Authority;
import cn.ccccltd.waf.message.thread.threadlocal.MessageContext;
import cn.ccccltd.waf.message.util.DateUtilsNew;
import cn.ccccltd.waf.message.util.MessageUtils;
import cn.ccccltd.waf.message.util.ToolUtils;
import cn.ccccltd.waf.message.util.sql.SqlContext;
import cn.ccccltd.waf.message.util.sql.SqlTools;
import cn.ccccltd.waf.message.web.service.UserRegister;

/**
 * 创建日期:2017年11月15日
 * Title: 用户查询实现
 * Description：对本文件的详细描述，原则上不能少于50字
 * @author yangjingjiang
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Component
public class UserRegisterImpl implements UserRegister {

	private static Logger log = LoggerFactory.getLogger(UserRegisterImpl.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public Object saveUser(Authority wma) {
		
		Assert.hasText(wma.getSendSystemid(),"系统id不能为空！");
		Assert.hasText(wma.getSystemName(),"系统名称不能为空！");
		
		if (StringUtils.isNotBlank(wma.getPhone())) {
			Assert.isTrue(ToolUtils.isPhone(wma.getPhone()),"手机号码错误！");
		}
		
		if (StringUtils.isNotBlank(wma.getEmail())) {
			Assert.isTrue(ToolUtils.isEmail(wma.getEmail()),"邮箱地址错误！");
		}
		
		//创建时间
		wma.setRegisterTime(DateUtilsNew.getDateTime());
		SqlContext insert = SqlTools.getInsert(wma);
		int count = 0;
		
		try {
			
			count = jdbcTemplate.update(insert.getSql(), insert.getParams());
			
		} catch (DuplicateKeyException e) {
			//截获系统id重复异常
			return new MessageResult("false", MessageConstants.ERR_HAS_DUPLICATE, "系统编码不能重复！");
			
		}
		
		log.info("cn.ccccltd.waf.message.web.service.impl.UserRegisterImpl.saveUser(Authority),保存用户成功，条数" + count + wma);
		//放置到权限缓存中
		AppInit.userMap.put(wma.getSendSystemid(),wma);
		
		return new MessageResult("true", "200", "保存成功！");
		
	}

	@Override
	public Object deleteUser(String id) {
		
		Assert.hasText(id, "未勾选需要删除内容!");
		
		MessageResult result = (MessageResult)getUserById(id);
		Authority wma = (Authority)result.getData();
		//是否是管理员
		if(MessageUtils.isAdmin(wma)) {
			Assert.isTrue(false, "不能删除管理员用户!");
		}
		wma.setDeleted(MessageConstants.TRUE_CHAR);
		//进行删除操作
		SqlContext delete = SqlTools.getUpdate(wma);
		int count = jdbcTemplate.update(delete.getSql(), id);
		
		log.info("cn.ccccltd.waf.message.web.service.impl.UserRegisterImpl.deleteUser(String),删除用户成功，条数" + count + wma);
		//从缓存中移除
		AppInit.userMap.remove(wma.getSendSystemid());
		
		return new MessageResult("true", "200", "删除成功！");
		
	}

	@Override
	public Object editUser(Authority wma) {
		
		MessageResult result = (MessageResult)getUserById(wma.getId());
		Authority wmaTemp = (Authority)result.getData();
		//获取当前请求人是否是管理员
		Authority wafMsgAuthority = (Authority)MessageContext.getValue(MessageConstants.SESSION);
		//判断是否是管理员
		if((!MessageUtils.isAdmin(wafMsgAuthority)) && MessageUtils.isAdmin(wmaTemp)) {
			Assert.isTrue(false, "不能修改管理员用户!");
		}

		if(StringUtils.isNotBlank(wma.getPhone())) {
			Assert.isTrue(ToolUtils.isPhone(wma.getPhone()),"手机号码错误！");
		}
		
		if(StringUtils.isNotBlank(wma.getEmail())) {
			Assert.isTrue(ToolUtils.isEmail(wma.getEmail()),"邮箱地址错误！");
		}
		
		SqlContext update = SqlTools.getUpdate(wma);
		
		int count = 0;
		try {
			count = jdbcTemplate.update(update.getSql(), update.getParams());
			
		} catch (DuplicateKeyException e) {
			
			return new MessageResult("false", MessageConstants.ERR_HAS_DUPLICATE, "系统编码不能重复！");
			
		}
		
		log.info("cn.ccccltd.waf.message.web.service.impl.UserRegisterImpl.editUser(Authority),更新用户成功，条数" + count + wma);
		//移除原来的系统权限，不能通过直接放置权限，如果系统id修改会出现多个权限
		AppInit.userMap.remove(wmaTemp.getSendSystemid());
		//将修改数据放到缓存中
		AppInit.userMap.put(wma.getSendSystemid(),wma);
		return new MessageResult("true", "200", "编辑成功！");
		
	}

	@Override
	public Object getUserById(String id) {
		
		Assert.hasText(id, "查询的主键为空!");
		
		//不进行数据过滤处理
		MessageContext.setValue(MessageConstants.NOTFILTERDATA, MessageConstants.TRUE);
		SqlContext byKey = SqlTools.getByKey(Authority.class,id);
		Authority wma = jdbcTemplate.queryForObject(byKey.getSql(), byKey.getParams(), new BeanPropertyRowMapper<>(Authority.class));
		
		return new MessageResult("true", "200", "查询成功！",wma);
		
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object getUserByPage(Map<String,Object> map) {
		
		//查询数据
		String select = SqlTools.getSelectAllProperty("", Authority.class);
		List<Authority> query = jdbcTemplate.query(select, new BeanPropertyRowMapper(Authority.class));
		
		//生成count的sql
		String sqlCount = SqlTools.getCountSql("waf_msg_authority");
		Long queryCount = jdbcTemplate.queryForObject(sqlCount, Long.class);
		
		//放置数据
		Data<Authority> dt = new Data<>();
		dt.setTotal(queryCount);
		dt.setRows(query);
		
		
		MessageResult rs = new MessageResult("true", "200", "加载数据成功！", dt);
		return rs;
		
	}

}
